package com.smt.take.ui.adapter

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.smt.take.R
import com.smt.take.model.beans.RecepitAddressBean
import com.smt.take.ui.activity.AddOrEditAddressActivity

class AddressRvAdapter(val context: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    var addressList = arrayListOf<RecepitAddressBean>()
    fun setAddList(list: ArrayList<RecepitAddressBean>) {
        this.addressList = list
        notifyDataSetChanged()
    }


    override fun getItemCount(): Int {
        return addressList.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        (holder as AddressItemHolder).bindData(addressList[position])
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val itemView =
            LayoutInflater.from(context).inflate(R.layout.item_receipt_address, parent, false)
        return AddressItemHolder(itemView)
    }

    inner class AddressItemHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val ivEdit: ImageView = itemView.findViewById(R.id.iv_edit) as ImageView
        private val tvName: TextView
        private val tvSex: TextView
        private val tvPhone: TextView
        private val tvLabel: TextView
        private val tvAddress: TextView
        lateinit var address: RecepitAddressBean

        init {
            ivEdit.setOnClickListener {
                val intent = Intent(context, AddOrEditAddressActivity::class.java)
                intent.putExtra("addressBean", address)
                context.startActivity(intent)
            }
            tvName = itemView.findViewById(R.id.tv_name) as TextView
            tvSex = itemView.findViewById(R.id.tv_sex) as TextView
            tvPhone = itemView.findViewById(R.id.tv_phone) as TextView
            tvLabel = itemView.findViewById(R.id.tv_label) as TextView
            tvAddress = itemView.findViewById(R.id.tv_address) as TextView
            itemView.setOnClickListener {
                val data = Intent()
                data.putExtra("address", address)
                (context as Activity).setResult(200, data)
                context.finish()
            }
        }

        @SuppressLint("SetTextI18n")
        fun bindData(address: RecepitAddressBean) {
            this.address = address
            tvName.text = address.username
            tvSex.text = address.sex
            tvPhone.text = address.phone + "," + address.phoneOther
            tvAddress.text = "${address.address},${address.detailAddress}"
            tvLabel.text = address.label
        }
    }

}